$(document).ready(function(){
	var k = [$('#k1'),$('#k2'),$('#k3'),$('#k4'),$('#k5')],
		belka = $('#belka'),
		licznik = 0,
		lives = k.length-1;

	function collision (k) {
		var x2b = parseInt(belka.css('left')) + parseInt(belka.css('width')) + 1,
		x1k = parseInt(k.css('left')),
		x1b = parseInt(belka.css('left')),
		x2k = parseInt(k.css('left')) + parseInt(k.css('width')),
		y1b = parseInt(belka.css('top')),
		y2k = parseInt(k.css('top')) + parseInt(k.css('height')) + 2;
		if ( (x2b<x1k) || (x1b>x2k)) {
				return false;
		}
		return (y1b==y2k);
	}
	$(window).bind("keydown", function(oEvent){
		var leftOffset = parseInt(belka.css('left')), 

		deltaX=10;
		if (oEvent.keyCode == 39 && leftOffset < 445 ) {
			belka.css('left', (leftOffset+deltaX) + 'px' );
		}
		
		if (oEvent.keyCode == 37 && leftOffset > 7 ) {
			belka.css('left', (leftOffset-deltaX) + 'px' );
		}
		
	});

	function incrementScore()
	{
		$('#score').html(++licznik);
	}

	function action (direction, ball, speed) {
		
		var top = parseInt(ball.css('top'));

		if (collision(ball) || top < 10) {
			incrementScore();
			direction = direction * (-1);
			if (top < 10 ) {
				ball.css('left', ((Math.random()*1000) % 440) + 'px');
			}
		}
		if (top < 290){
			ball.css('top', (top + direction) + 'px');
			setTimeout(function() { action (direction, ball, speed); }, speed);
		}
		else {
			ball.remove();
			lives--;
			if (lives==0) {
					saveResult(licznik);
			}
		}
	}

	action(1, k[0], 5);
	action(-1, k[1], 17);
	action(-1, k[2], 21);
	action(-1, k[3], 10);
	action(-1, k[4], 7);
	
	
	function saveResult (result){
		var nick = $('#nick').val();
		
		$.ajax({
            url    : 'ajax.php?result='+parseInt(result) + "&nick=" + nick,
            success: function(data) {
                alert(data);
            }
        });
	}
	
	
});



